package cn.edu.neusoft.neufooddemo.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.edu.neusoft.neufooddemo.R;
import cn.edu.neusoft.neufooddemo.bean.LoginBean;
import cn.edu.neusoft.neufooddemo.listener.RetrofitListener;
import cn.edu.neusoft.neufooddemo.model.UserModel;

/*import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;*/

public class LoginActivity extends BaseActivity implements View.OnClickListener,RetrofitListener<LoginBean>{
    private String AppId="1106189944";
    private Button btn_login;
//    private ImageButton qq_login;
    private TextView tv_reg,tv_phone_reg;
    private EditText username, userpass;
    private CheckBox cb_remember;
 //   Tencent   mTencent;

    void login() {
        UserModel userModel = new UserModel();
       userModel.userLogin(username.getText().toString().trim(), userpass.getText().toString().trim(),this);
    }
    @Override
    public void onSuccess(LoginBean userId,int flag) {
        System.out.println("==========================="+userId);
        if (userId.getUserid().equals("0")) {
            showToast("用户名或密码错误");
        } else {
            saveUser(userId.getUserid());
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            showToast("登录成功");
        }
    }
    @Override
    public void onFail() {
        showToast("网络发生错误");
    }


    protected void initViews() {
        setLayout(R.layout.activity_login);
        username = (EditText) findViewById(R.id.user);
        userpass = (EditText) findViewById(R.id.password);
        btn_login = (Button) findViewById(R.id.login);
//        qq_login = (ImageButton) findViewById(R.id.qqLogin);
        tv_reg = (TextView) findViewById(R.id.reg);
        tv_phone_reg = (TextView) findViewById(R.id.phone_reg);
        cb_remember=(CheckBox)findViewById(R.id.cb_remember);
    }

    void initEvents() {
        btn_login.setOnClickListener(this);
        tv_reg.setOnClickListener(this);
//        qq_login.setOnClickListener(this);
        tv_phone_reg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.login:
                if (username.getText().toString().trim().equals("") || userpass.getText().toString().trim().equals("")) {
                    Toast.makeText(LoginActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    login();
                }
                break;
            case R.id.reg:
                Intent intent1 = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivityForResult(intent1, 1);
                break;
           /* case R.id.qqLogin:
                   mTencent = Tencent.createInstance(AppId,getApplicationContext());
                mTencent.login(LoginActivity.this,"all",new BaseUiListener());
                break;*/
            case R.id.phone_reg:
                Intent intent2 = new Intent(LoginActivity.this, PhoneRegActivity.class);
                startActivity(intent2);
                break;
        }
    }

    void initData()
    {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        if(sp.getBoolean("isRemember",false))
        {
            username.setText(sp.getString("username",""));
            userpass.setText(sp.getString("userpass",""));
            cb_remember.setChecked(true);
        }else
        {
            username.setText("");
            userpass.setText("");
            cb_remember.setChecked(false);
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==RESULT_OK)
        {
            String et_user = data.getStringExtra("user");
            username.setText(et_user);
        }
     /*   Tencent.onActivityResultData(requestCode, resultCode, data, new BaseUiListener());

        if(requestCode == Constants.REQUEST_API) {
            if(resultCode == Constants.REQUEST_LOGIN) {
                Tencent.handleResultData(data, new BaseUiListener());
            }
        }*/
    }

    public void saveUser(String user_id) {
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
        if(cb_remember.isChecked())
            editor.putBoolean("isRemember",true);
        else
            editor.putBoolean("isRemember",false);
        editor.putString("username", username.getText().toString());
        editor.putString("user_id", user_id);
        editor.putString("userpass", userpass.getText().toString());
        editor.commit();//提交修改
    }

   /* private class BaseUiListener implements IUiListener {


//这个类需要实现三个方法 onComplete（）：登录成功需要做的操作写在这里
// onError onCancel 方法具体内容自己搜索

        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
            try {
                //获得的数据是JSON格式的，获得你想获得的内容
                //如果你不知道你能获得什么，看一下下面的LOG
                Log.v("----TAG--", "-------------"+response.toString());
                String openidString = ((JSONObject) response).getString("openid");
                mTencent.setOpenId(openidString);
//                saveUser("44","text","text",1);
                saveUser("44");
                mTencent.setAccessToken(((JSONObject) response).getString("access_token"),((JSONObject) response).getString("expires_in"));


                Log.v("TAG", "-------------"+openidString);
                //access_token= ((JSONObject) response).getString("access_token");
                //expires_in = ((JSONObject) response).getString("expires_in");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            *//**到此已经获得OpneID以及其他你想获得的内容了
             QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
             sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
             如何得到这个UserInfo类呢？
             *//*

            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);

            //    info.getUserInfo(new BaseUIListener(this,"get_simple_userinfo"));
            info.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {
                    //用户信息获取到了
                    try {
                        Log.v("用户名", ((JSONObject) o).getString("nickname"));
                        Log.v("用户姓名", ((JSONObject) o).getString("gender"));
                        Log.v("UserInfo",o.toString());
                        Intent intent1 = new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent1);
                        finish();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(UiError uiError) {
                    Log.v("UserInfo","onError");
                }

                @Override
                public void onCancel() {
                    Log.v("UserInfo","onCancel");
                }
            });



        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext(), "onError", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(), "onCancel", Toast.LENGTH_SHORT).show();
        }


    }*/
}

